package com.zoe.wan.base.loading

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.blankj.utilcode.util.ActivityUtils
import java.lang.ref.WeakReference

object LoadingUtils {
    private var activity: WeakReference<Activity>? = null
    private var loadingDialog: LoadingDialog? = null

    fun init(application: Application) {
        application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(p0: Activity, p1: Bundle?) {

            }

            override fun onActivityStarted(p0: Activity) {

            }

            override fun onActivityResumed(p0: Activity) {
                LoadingUtils.activity = WeakReference(p0)
            }

            override fun onActivityPaused(p0: Activity) {

            }

            override fun onActivityStopped(p0: Activity) {

            }

            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {

            }

            override fun onActivityDestroyed(p0: Activity) {

            }

        })
    }

    fun showLoading() {
//        if (loadingDialog == null) {
//            this.activity?.let {
//                it.get()?.let { c ->
//                    loadingDialog = LoadingDialog(c)
//                }
//            }
//        }
        if (loadingDialog != null && loadingDialog?.dialogShowing() == true) {
            return
        }
        loadingDialog = LoadingDialog(ActivityUtils.getTopActivity())
        loadingDialog?.showLoading()
    }

    fun dismissLoading() {
        loadingDialog?.dismissLoading()
    }
}